import flash.events.Event;
import mx.charts.ChartItem;
import mx.charts.HitData;
import mx.charts.events.ChartItemEvent;
import mx.charts.series.items.ColumnSeriesItem;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.DateField;
import mx.events.FlexEvent;
import mx.events.ListEvent;
import mx.formatters.DateFormatter;
import mx.graphics.IFill;
import mx.graphics.SolidColor;
import mx.managers.PopUpManager;
import mx.managers.ToolTipManager;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
[Bindable]
private var acDaily:ArrayCollection;
[Bindable]
private var acMonthly:ArrayCollection;
[Bindable]
private var acChangeD:ArrayCollection;
[Bindable]
private var acChangeM:ArrayCollection;
private var uri:String;

private function init():void
{
	acDaily = new ArrayCollection();
	acMonthly = new ArrayCollection();
	acChangeD = new ArrayCollection();
	acChangeM = new ArrayCollection();
	electricid = Application.application.parameters.electricid;
	trace(electricid);
	if (electricid.length == 0)
	{
		Alert.show("尚未取得電號，請登入");
		return;
	}
	var loader:URLLoader = new URLLoader();
	loader.addEventListener(Event.COMPLETE, configLoad);
	loader.dataFormat = URLLoaderDataFormat.TEXT;
	loader.load(new URLRequest('config.xml'));
}

private function configLoad(event:Event):void
{
	var loader:URLLoader = event.currentTarget as URLLoader;
	var xml:XML          = new XML(loader.data);
	uri = xml.Analysis;
	createSelectorData();
	cbSelector.addEventListener(ListEvent.CHANGE, selectorChange);
}

private function createSelectorData():void
{
	ToolTipManager.showDelay = 400;
	ToolTipManager.hideDelay = 2000;
	acSelector = new ArrayCollection();
	var now:Date = new Date();
	for (var i:int; i < 12; i++)
	{
		var date:Date   = new Date(now.fullYear, now.month - i, 1);
		var item:Object = new Object();
		item.label = getYearMonthC(date);
		item.data = date;
		acSelector.addItem(item);
	}
	acSelector.refresh();
	selectorChange(new ListEvent(ListEvent.CHANGE));
}

private function selectorChange(event:ListEvent):void
{
	var item:Object = cbSelector.selectedItem;
	passionMonth(item.data as Date);
}

private function passionMonth(start:Date):void
{
	var now:Date = new Date();
	if (start.getTime() > now.getTime())
	{
		alertStartError();
		return;
	}
	getData(start);
}

private function colorFunc(item:ChartItem, index:Number):IFill
{
	var data:Object = item.item;
	var w:Number    = data.Weekend;
	if (w > 5)
	{
		return new SolidColor(weekend);
	}
	else
	{
		return new SolidColor(normal);
	}
}

private function getData(start:Date):void
{
	var service:HTTPService = new HTTPService();
	service.showBusyCursor = true;
	var siteUrl:String = uri;
	var s:String       = getFullDate(start);
	siteUrl += "?starttime=" + s;
	siteUrl += "&electricid=" + electricid;
	service.url = siteUrl;
	strTimeRange = s;
	service.addEventListener(ResultEvent.RESULT, getResult);
	newLoading();
	service.send();
}

private function newLoading():void
{
	loading = PopUpManager.createPopUp(this, loadingBox, true) as loadingBox;
	loading.x = (this.width - loading.width) / 2;
	loading.y = (this.height - loading.height) / 2;
}

private function delLoading():void
{
	if (loading != null)
	{
		PopUpManager.removePopUp(loading);
		loading = null;
	}
}

private function getResult(event:ResultEvent):void
{
	/** data
	 * 		day
	 * 			column
	 * 				TimeStamp
	 * 				Max
	 * 				Min
	 * 				Avg
	 * 				Weekend
	 * 		month
	 * 			column
	 * 				TimeStamp
	 * 				Max
	 * 				Min
	 * 				Avg
	 * 				Weekend
	 * 		changeD
	 * 			colume
	 * 				TimeStamp
	 * 				Variation
	 * 				Weekend
	 * 		changeM
	 * 			colume
	 * 				TimeStamp
	 * 				Variation
	 * 				Weekend
	 * 		ranking
	 * 			Rank
	 * 			TotalCustomer
	 * 		green
	 * 			Total_CO2
	 * 			Total_Tree
	 * 			Total_Gasoline
	 * end of data */
	delLoading();
	var item:Object;
	var data:Object = event.result.data;
	item = data.green;
	//	Green
	strCO2 = Number(item.total_co2).toFixed(2);
	strTREE = Number(item.total_gasoline).toFixed(2);
	strGAS = Number(item.total_tree).toFixed(2);
	//	Ranking
	item = data.ranking;
	strRank = item.Rank;
	strTotal = item.TotalCustomer;
	while (strTotal.length < 10)
	{
		strTotal = '0' + strTotal;
	}
	while (strRank.length < 3)
	{
		strRank = '0' + strRank;
	}
	//	Day
	item = data.changeD;
	setChangeD(item.bar as ArrayCollection);
	//	Month
	item = data.changeM;
	setChangeM(item.bar as ArrayCollection);
	item = data.daily;
	setDaily(item.bar as ArrayCollection);
	item = data.monthly;
	setMonthly(item.bar as ArrayCollection);
}

private function setDaily(source:ArrayCollection):void
{
	processDate(source);
	acDaily = source;
}

private function setMonthly(source:ArrayCollection):void
{
	processDate(source);
	acMonthly = source;
}

private function setChangeD(source:ArrayCollection):void
{
	processDate(source);
	acChangeD = source;
}

private function setChangeM(source:ArrayCollection):void
{
	processDate(source);
	acChangeM = source;
}

private function processDate(source:ArrayCollection):void
{
	var item:Object;
	for each (item in source)
	{
		var temp:String = item.TimeStamp;
		temp = temp.replace(/-/g, "/");
		var num:Number = Date.parse(temp);
		item.TimeStamp = new Date(num);
	}
}

private function lblDaily(value:Date, lastValue:Date, asix:DateTimeAxis):String
{
	return getYearMonthDayC(value);
}

private function lblMonthly(value:Date, lastValue:Date, asix:DateTimeAxis):String
{
	return getYearMonthC(value);
}

private function chartTipD(e:HitData):String
{
	var result:String = '';
	var item:Object   = e.item;
	result += "\n" + "時間：" + getYearMonthDayC(item.TimeStamp);
	result += "\n" + "最大用電：" + (Number(item.Max)).toFixed(2) + " kWh";
	result += "\n" + "最小用電：" + (Number(item.Min)).toFixed(2) + " kWh";
	result += "\n" + "平均用電：" + (Number(item.Avg)).toFixed(2) + " kWh";
	return result;
}

private function chartTipM(e:HitData):String
{
	var result:String = '';
	var item:Object   = e.item;
	result += "\n" + "時間：" + getYearMonthC(item.TimeStamp);
	result += "\n" + "最大用電：" + (Number(item.Max)).toFixed(2) + " kWh";
	result += "\n" + "最小用電：" + (Number(item.Min)).toFixed(2) + " kWh";
	result += "\n" + "平均用電：" + (Number(item.Avg)).toFixed(2) + " kWh";
	return result;
}

private function tipChangeD(e:HitData):String
{
	var result:String = '';
	var item:Object   = e.item;
	result += "\n" + "時間：" + getYearMonthDayC(item.TimeStamp);
	result += "\n" + "變動：";
	var n:Number = item.Variation;
	if (n > 0)
	{
		result += '上升';
	}
	else
	{
		result += '下降';
	}
	n = Math.abs(n);
	result += n.toFixed(2) + "％";
	return result;
}

private function tipChangeM(e:HitData):String
{
	var result:String = '';
	var item:Object   = e.item;
	result += "\n" + "時間：" + getYearMonthC(item.TimeStamp);
	result += "\n" + "變動：";
	var n:Number = item.Variation;
	if (n > 0)
	{
		result += '上升';
	}
	else
	{
		result += '下降';
	}
	n = Math.abs(n);
	result += n.toFixed(2) + "％";
	return result;
}

private function alertStartError():void
{
	Alert.show(startError);
}
